# Makefile for code evaluation module

# 定义库文件名称和平台特定后缀
ifeq ($(OS),Windows_NT)
    LIB_NAME = eval_code2
    LIB_SUFFIX = .dll
	LIB_DIR = ../lib
else
    UNAME_S := $(shell uname -s)
    ifeq ($(UNAME_S),Darwin)
        LIB_NAME = libeval_code2
        LIB_SUFFIX = .dylib
		LIB_DIR = ../lib
    else
        LIB_NAME = libeval_code2
        LIB_SUFFIX = .so
		LIB_DIR = ../lib
    endif
endif

# 链接库名称
LIB_FILE = $(LIB_NAME)$(LIB_SUFFIX)

# 目标库文件位置
TARGET_LIB = $(LIB_DIR)/$(LIB_FILE)
LOCAL_LIB = $(LIB_FILE)

# 编译器和编译选项
CC = gcc
ifeq ($(OS),Windows_NT)
    CFLAGS = -Wall -shared -I../vm -I../lexer -I../parser -I../core
    # Windows下直接指定完整的库文件路径，不使用-l选项
    LDFLAGS = ../lib/core2.dll ../lib/cvm2.dll ../lib/clexer2.dll ../lib/cparser2.dll
    EXE_SUFFIX = .exe
else
    ifeq ($(UNAME_S),Darwin)
        CFLAGS = -Wall -dynamiclib -fPIC -I../vm -I../lexer -I../parser -I../core
        LDFLAGS = -L../$(LIB_DIR) -lcvm2 -lclexer2 -lcparser2 -lcore2
        EXE_SUFFIX = 
    else
        CFLAGS = -Wall -shared -fPIC -I../vm -I../lexer -I../parser -I../core
        LDFLAGS = -L../$(LIB_DIR) -lcvm2 -lclexer2 -lcparser2 -lcore2
        EXE_SUFFIX = 
    endif
endif

# 源文件
SRC = eval_code.c
EXE_SRC = eval_excute.c

# 对象文件
OBJ = eval_code.o

# 默认目标：编译并生成库文件和可执行文件
all: $(TARGET_LIB) $(LOCAL_LIB) eval_excute$(EXE_SUFFIX)

# 编译源文件为对象文件
$(OBJ): $(SRC)
	@echo "编译 $<..."
	@$(CC) $(CFLAGS) -c $< -o $@

# 链接对象文件生成库文件并复制到lib目录
$(TARGET_LIB): $(OBJ)
	@echo "链接库文件 $(LIB_FILE)..."
	@$(CC) $(CFLAGS) $(OBJ) -o $(LIB_FILE) $(LDFLAGS)
	@mkdir -p $(LIB_DIR)
	@cp $(LIB_FILE) $(LIB_DIR)/
	@echo "库文件已复制到 $(LIB_DIR)/$(LIB_FILE)"

# 在当前目录也生成一个库文件
$(LOCAL_LIB): $(TARGET_LIB)
	@echo "本地库文件已生成: $(LOCAL_LIB)"

# 添加编译eval_excute的规则
eval_excute$(EXE_SUFFIX): $(EXE_SRC) $(OBJ) $(LOCAL_LIB)
	@echo "编译 eval_excute$(EXE_SUFFIX)..."
	$(CC) -o eval_excute$(EXE_SUFFIX) $(EXE_SRC) $(OBJ) -I../lexer -I../parser -I../vm -L../lib -lclexer2 -lcparser2 -lcvm2 -lcore2 -Wl,-rpath,../lib

# 添加编译eval_test的规则
eval_test$(EXE_SUFFIX): eval_test.c $(OBJ) $(LOCAL_LIB)
	@echo "编译 eval_test$(EXE_SUFFIX)..."
	$(CC) -o eval_test$(EXE_SUFFIX) eval_test.c $(OBJ) -I../lexer -I../parser -I../vm -L../lib -lclexer2 -lcparser2 -lcvm2 -lcore2 -Wl,-rpath,../lib


# 测试目标
test: eval_test$(EXE_SUFFIX)
	./eval_test$(EXE_SUFFIX) test.c

# 清理目标也应包含eval_excute
clean:
	@echo "清理code_eval模块..."
	@rm -f $(OBJ) $(LIB_FILE)
	@rm -f $(LIB_DIR)/$(LIB_FILE)
	@rm -f eval_test$(EXE_SUFFIX) eval_excute$(EXE_SUFFIX)
	@echo "清理完成"

.PHONY: all clean